#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash blat.35.1.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar environment-modules libatomic libpng-devel 

if `wget -t 40 -c -P $buildpath  https://ghproxy.com/https://github.com/djhshih/blat/archive/refs/tags/v35.1.tar.gz`
then 
   echo "v35.1.tar.gz下载成功!(国内github加速下载)"
elif `wget -t 40 -c -P $buildpath  https://github.com/djhshih/blat/archive/refs/tags/v35.1.tar.gz`
then 
   echo "v35.1.tar.gz下载成功!"
else
   echo "v35.1.tar.gz下载失败!"
fi
tar xf "$buildpath"/v35.1.tar.gz -C "$buildpath" && rm -rf "$buildpath"/v35.1.tar.gz

mkdir -p "$installpath"/blat-35.1 && cp -r $buildpath/blat-35.1/* "$installpath"/blat-35.1
cd "$installpath"/blat-35.1 && export MACHTYPE=aarch64
sed -i "121c extern jmp_buf htmlRecover;" src/inc/htmshell.h

DESTDIR="$installpath"/blat-35.1 make -j$(nproc) CC=clang
cat>"$installpath/blat-35.1/blat_modulefiles"<<EOF 
#%Module1.0
conflict blat
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set BLAT \$pwd
setenv BLAT \$BLAT
prepend-path PATH \$BLAT/bin
EOF

rm -rf "$buildpath"/blat-35.1

